/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { FileSet } from '@ohos/hvigor';
import { TaskInputValue } from '@ohos/hvigor';
import { hvigorCore } from '@ohos/hvigor';
import { createHash } from 'crypto';
import * as fse from 'fs-extra';
import * as path from 'path';

import { LegacyPathInfo } from '../../common/legacy-path-info.js';
import { BuildArtifactConst } from '../../const/build-directory-const.js';
import { InjectConst } from '../../const/inject-const.js';
import { LegacyModuleModelImpl } from '../../model/module/legacy-module-model-impl.js';
import { ConfigJson } from '../../options/configure/config-json-options.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';
import LegacyFATask = TaskNames.LegacyFATask;
import { LegacyHookCompileResource } from './hook/legacy-hook-compile-resource.js';
import ConfigOptObj = ConfigJson.ConfigOptObj;
import { cloneDeep } from '@baize/wdk';

const PAGE = InjectConst.PREVIEWER_REPLACE_PAGE;

/**
 * 为har生成一个假的manifest
 *
 * @since 2022/3/1
 */
export class LegacyGenerateHarJsManifest extends OhosHapTask {
  private _log: OhosLogger = OhosLogger.getLogger(LegacyGenerateHarJsManifest.name);
  private previewPage: string | undefined = hvigorCore.getExtraConfig().get(PAGE);
  private readonly _moduleModel: LegacyModuleModelImpl;
  private readonly _configOpt: ConfigOptObj;
  private readonly _minPlatformVersion: number;

  constructor(taskService: TargetTaskService) {
    super(taskService, LegacyFATask.GENERATE_HAR_JS_MANIFEST);
    this._moduleModel = this.service.getModuleModel()! as LegacyModuleModelImpl;
    this._configOpt = cloneDeep(this._moduleModel.getJsonObjByTargetName(this.targetData.getTargetName()));
    this._minPlatformVersion = this.targetData.getCompatibleApiVersion();
  }

  initTaskDepends() {
    this.declareDepends(LegacyHookCompileResource.name);
  }

  private static getWindowObj(): object {
    return {
      autoDesignWidth: false,
      designWidth: 454,
    };
  }

  declareInputs(): Map<string, TaskInputValue> {
    const inputs = new Map<string, TaskInputValue>();
    const configHash: string = createHash('MD5')
      .update(`${JSON.stringify(this._configOpt)}`)
      .digest('hex');
    inputs.set('CONFIG_OBJ', configHash);
    inputs.set('MIN_PLATFORM_VERSION', this._minPlatformVersion);
    if (this.previewPage) {
      inputs.set('PREVIEW_PAGE', this.previewPage);
    }
    return inputs;
  }

  declareOutputFiles(): FileSet {
    return new FileSet().addEntry(this.targetData.getPathInfo().getIntermediatesLegacyManifestJson());
  }

  protected doTaskAction(): void {
    this.generateJsonInfo(this._configOpt, this.pathInfo);
  }

  private getManifestPages(): string[] {
    if (!this.previewPage) {
      return [];
    }
    this._log.debug(`generate ${this.previewPage} for manifest.`);
    return [this.previewPage];
  }

  private generateJsonInfo(configJsonObj: ConfigJson.ConfigOptObj, targetPathInfo: LegacyPathInfo): void {
    const manifestObj: object = {
      appID: configJsonObj.app.bundleName,
      versionName: configJsonObj.app.version.name,
      versionCode: configJsonObj.app.version.code,
      minPlatformVersion: this._minPlatformVersion,
      appName: '',
      deviceType: configJsonObj.module.deviceType,
      window: LegacyGenerateHarJsManifest.getWindowObj(),
      pages: this.getManifestPages(),
    };

    this._log._printDebugCommand('JsManifest', manifestObj);
    const manifestFile = path.resolve(targetPathInfo.getIntermediatesLegacyManifestJson(), BuildArtifactConst.LEGACY_MANIFEST_JSON);
    fse.outputJSONSync(manifestFile, manifestObj);
  }
}
